import { isRef, onMounted, onUnmounted, toValue } from 'vue';
import { useDebounce } from '@/hooks/index.js';

/**
 * @description 监听窗口大小变化
 *
 * @param element 监听目标
 * @param callback 回调函数
 * @param delay
 * @returns {ResizeObserver} ResizeObserver实例
 */
export function useResize(element, callback, delay = 1000) {
  const onCallback = useDebounce(callback, delay);

  const resizeObserver = new ResizeObserver(([entry]) => onCallback(entry));

  onMounted(() => {
    const target = isRef(element) ? toValue(element) : element;
    resizeObserver?.observe(target);
  });

  onUnmounted(() => {
    resizeObserver.disconnect();
  });

  return resizeObserver;
}
